package cn.bitkit.component.context;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.bitkit.base.exception.BusinessAssert;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 	Spring上下文
 * @author changbo
 *
 */
public class SpringContext implements ApplicationContextAware {
	
	@Getter
    private static ApplicationContext context = null;

	@Override
	public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
		SpringContext.context = applicationContext;
	}
	
	public static <T> T getAssertedBean(Class<T> clazz){
        T t = getContext().getBean(clazz);
        BusinessAssert.isNotNull(t, "bean not found:"+clazz.getName());
        return t;
	}

    public static <T> T getBean(Class<T> clazz){
        return getContext().getBean(clazz);
    }
	
	public static <T> List<T> getBeanByType(Class<T> superClass){
		try {
			Map<String, T> beans = getContext().getBeansOfType(superClass);
			return new ArrayList<>(beans.values());
		}catch (Exception e) {
			return null;
		}
	}

}
